import { HttpClient } from "@angular/common/http";
import { Component } from "@angular/core";

@Component({
  selector: "app-tab3",
  templateUrl: "tab3.page.html",
  styleUrls: ["tab3.page.scss"],
})
export class Tab3Page {
  constructor(public http: HttpClient) {}

  data: Data[] = [];

  updateCount(index: number, delta: number) {
    const { iid, count } = this.data[index];
    // count: 是字符串类型
    const url = `/api/data/cart/update_count.php?iid=${iid}&count=${
      parseInt(count) + delta
    }`;

    this.http.get(url).subscribe((res: any) => {
      console.log(res);
      if (res.code == 200) {
        // count是字符串类型,  TS类型严格, 赋值必须是字符串
        this.data[index].count = parseInt(count) + delta + "";
      }
    });
  }

  doDel(index: number) {
    const iid = this.data[index].iid;

    const url = "/api/data/cart/del.php?iid=" + iid;

    this.http.get(url, { withCredentials: true }).subscribe((res: any) => {
      console.log(res);
      if (res.code == 200) {
        this.data.splice(index, 1);
      }
    });
  }

  ionViewWillEnter() {
    //ionic的生命周期: 页面显示时触发.  每次tab切换过来都会触发
    const url = "/api/data/cart/list.php";

    // 凡是用到 cookie 的请求, 都必须添加 信任
    this.http.get(url, { withCredentials: true }).subscribe((res: any) => {
      console.log(res);

      this.data = res.data;
    });
  }

  // ngOnInit: 组件初始化时触发一次
  ngOnInit(): void {}
}

///////////////////////////////
interface Data {
  count: string;
  iid: string;
  lid: string;
  pic: string;
  price: string;
  spec: string;
  title: string;
}
